package com.my.hzb.common.interceptor;


import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.my.hzb.common.bean.GlobalBean;
import com.my.hzb.common.bean.LoginUserBean;
import com.my.hzb.common.bean.ResultBean;
import com.my.hzb.common.util.CommonUtil;
import com.my.hzb.common.util.JsonUtil;
import com.my.hzb.common.util.MemcachedUtil;

public class LoginInterceptor extends HandlerInterceptorAdapter{

	@Autowired
	private MemcachedUtil memcachedUtil;
	
	public final boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
		try {
			String url = request.getRequestURI();
			getHeadersInfo(request);
			request.getHeaderNames().toString();
			System.out.println(request.getHeader("accept"));
			
			
			
			if(CommonUtil.isInterface(strList, url)){
				return true;
			}
//			if(null!=url&&null!=strList){
//				if(url.indexOf(".")>-1){
//					url = url.substring(0, url.indexOf("."));
//				}
//				for(String urll:strList){
//					if(urll.endsWith("/")){
//						if(url.indexOf(urll)>-1){
//							return true;
//						}
//					}else{
//						if(url.endsWith(urll)){
//							return true;
//						}
//					}
//				}
//			}
			String cookie = CommonUtil.getCookieByName(request,GlobalBean.loginCookie);
			if(null!=cookie){
				LoginUserBean cooUser = (LoginUserBean)JsonUtil.jsonToBean(CommonUtil.base64decode(cookie), LoginUserBean.class);
				if(null!=cooUser&&null!=cooUser.getUserName()){
					LoginUserBean meUser = (LoginUserBean)JsonUtil.jsonToBean(CommonUtil.base64decode((String)memcachedUtil.get(cooUser.getUserName())),LoginUserBean.class);
					if(cooUser.getSessionId().equals(meUser.getSessionId()))
					{
						if((new Date().getTime()-cooUser.getCreateTime().getTime())/60000<=30){
							return true;
						}
					}
				}
			}
//			Cookie[] cookies = request.getCookies();
//			if(null!=cookies){
//				for(Cookie coo:cookies){
//					if(GlobalBean.loginCookie.equals(coo.getName())){
//						
//					}
//				}
//			}
			if (request.getHeader("accept") != null 
					&& request.getHeader("accept").equalsIgnoreCase("*/*")){
				//如果是ajax请求响应头会有x-requested-with
				System.out.println("ajax");
				ResultBean result = new ResultBean(ResultBean.RETURN_ERROR_CODE,"请登录");
				result.setReturnObj("this is the url");
				String data = JsonUtil.objectToJson(result);  
		        OutputStream ps = response.getOutputStream();  
		        //这句话的意思，使得放入流的数据是utf8格式  
		        ps.write(data.getBytes("UTF-8"));
			}else{
				response.sendRedirect("/login.jsp");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
        return false;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)  {

    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)  {
    }
    
    private List<String> strList;

	public List<String> getStrList() {
		return strList;
	}
	public void setStrList(List<String> strList) {
		this.strList = strList;
	}
	private Map<String, String> getHeadersInfo(HttpServletRequest request) {
	    Map<String, String> map = new HashMap<String, String>();
	    Enumeration headerNames = request.getHeaderNames();
	    while (headerNames.hasMoreElements()) {
	        String key = (String) headerNames.nextElement();
	        String value = request.getHeader(key);
	        map.put(key, value);
	    }
	    System.out.println(map.toString());
	    return map;
	  }
}
